package com.lsx143.realtime.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.lsx143.realtime.app.BaseAppV2;
import com.lsx143.realtime.bean.VisitorStats;
import com.lsx143.realtime.common.Constants;
import com.lsx143.realtime.util.MyUtil;
import com.lsx143.realtime.util.SinkUtil;
import com.lsx143.realtime.util.WriteUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Map;

public class DWSVisitorStatsApp extends BaseAppV2 {
    public static void main(String[] args) {
        new DWSVisitorStatsApp().init(
                30001,
                "DWSVisitorStat",
                1,
                "DWSVisitorStat",
                Constants.TOPIC_DWD_PAGE_LOG,
                Constants.TOPIC_DWM_UV,
                Constants.TOPIC_DWM_JV
        );
    }

    @Override
    protected void run(StreamExecutionEnvironment env, Map<String, DataStreamSource<String>> srcStreams) {
        //1.得到union后的流
        DataStream<VisitorStats> unionStreams = parseAndUnionStreams(srcStreams);

        //2.开窗聚合
        SingleOutputStreamOperator<VisitorStats> reducedStream = aggregateStream(unionStreams);

        //3.写出到clickhouse
        WriteUtil.writeToClickHouse(reducedStream, Constants.CLICKHOUSE_TABLE_VISITOR_STATS, VisitorStats.class);
    }

    private SingleOutputStreamOperator<VisitorStats> aggregateStream(DataStream<VisitorStats> unionStreams) {
        return unionStreams
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<VisitorStats>forBoundedOutOfOrderness(Duration.ofSeconds(20))
                                .withTimestampAssigner((vs, ts) -> vs.getTs())
                )
                //根据维度组成的字符串分组
                .keyBy(vs -> vs.getVc() + "_" + vs.getCh() + "_" + vs.getAr() + vs.getIs_new())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<VisitorStats>() {
                            @Override
                            public VisitorStats reduce(VisitorStats vs1,
                                                       VisitorStats vs2) {
                                //聚合度量字段
                                vs1.setUv_ct(vs1.getUv_ct() + vs2.getUv_ct());
                                vs1.setPv_ct(vs1.getPv_ct() + vs2.getPv_ct());
                                vs1.setSv_ct(vs1.getSv_ct() + vs2.getSv_ct());
                                vs1.setUj_ct(vs1.getUj_ct() + vs2.getUj_ct());
                                vs1.setDur_sum(vs1.getDur_sum() + vs2.getDur_sum());
                                return vs1;
                            }
                        },
                        new ProcessWindowFunction<VisitorStats, VisitorStats, String, TimeWindow>() {
                            @Override
                            public void process(String key,
                                                Context ctx,
                                                Iterable<VisitorStats> iterable,
                                                Collector<VisitorStats> out) {
                                //获取聚合后的结果
                                VisitorStats vs = iterable.iterator().next();
                                //添加窗口时间
                                vs.setStt(MyUtil.toDateTime(ctx.window().getStart()));
                                vs.setEdt(MyUtil.toDateTime(ctx.window().getEnd()));
                                //更新ts
                                vs.setTs(ctx.currentProcessingTime());
                                out.collect(vs);
                            }
                        }
                );

    }

    /**
     * 解析和union多个指标的stream
     *
     * @param srcStreams 数据流map
     * @return DataStream<VisitorStats>
     */
    private DataStream<VisitorStats> parseAndUnionStreams(Map<String, DataStreamSource<String>> srcStreams) {
        //1.pv和持续时间
        SingleOutputStreamOperator<VisitorStats> pvAndDurationStream = srcStreams
                .get(Constants.TOPIC_DWD_PAGE_LOG)
                .map(line -> {
                    JSONObject obj = JSONObject.parseObject(line);
                    JSONObject common = obj.getJSONObject("common");
                    //得到基本维度信息
                    String vc = common.getString("vc");
                    String ch = common.getString("ch");
                    String ar = common.getString("ar");
                    String is_new = common.getString("is_new");

                    Long ts = obj.getLong("ts");
                    Long dur_sum = obj.getJSONObject("page").getLong("during_time");

                    return new VisitorStats(
                            "", "",
                            vc, ch, ar, is_new,
                            0L, 1L, 0L, 0L, dur_sum,
                            ts);
                });

        //2.uv
        SingleOutputStreamOperator<VisitorStats> uvStream = srcStreams
                .get(Constants.TOPIC_DWM_UV)
                .map(line -> {
                    JSONObject obj = JSONObject.parseObject(line);
                    JSONObject common = obj.getJSONObject("common");
                    //得到基本维度信息
                    String vc = common.getString("vc");
                    String ch = common.getString("ch");
                    String ar = common.getString("ar");
                    String is_new = common.getString("is_new");

                    Long ts = obj.getLong("ts");

                    return new VisitorStats(
                            "", "",
                            vc, ch, ar, is_new,
                            1L, 0L, 0L, 0L, 0L,
                            ts);
                });

        //3.jv
        SingleOutputStreamOperator<VisitorStats> jvStream = srcStreams
                .get(Constants.TOPIC_DWM_JV)
                .map(line -> {
                    JSONObject obj = JSONObject.parseObject(line);
                    JSONObject common = obj.getJSONObject("common");
                    //得到基本维度信息
                    String vc = common.getString("vc");
                    String ch = common.getString("ch");
                    String ar = common.getString("ar");
                    String is_new = common.getString("is_new");

                    Long ts = obj.getLong("ts");

                    return new VisitorStats(
                            "", "",
                            vc, ch, ar, is_new,
                            0L, 0L, 0L, 1L, 0L,
                            ts);
                });

        //4.sv
        SingleOutputStreamOperator<VisitorStats> svStream = srcStreams
                .get(Constants.TOPIC_DWD_PAGE_LOG)
                .flatMap(new FlatMapFunction<String, VisitorStats>() {
                    @Override
                    public void flatMap(String line,
                                        Collector<VisitorStats> out) {
                        JSONObject obj = JSONObject.parseObject(line);
                        if (obj.getJSONObject("page").getString("last_page_id") == null) {
                            JSONObject common = obj.getJSONObject("common");
                            //得到基本维度信息
                            String vc = common.getString("vc");
                            String ch = common.getString("ch");
                            String ar = common.getString("ar");
                            String is_new = common.getString("is_new");

                            Long ts = obj.getLong("ts");

                            out.collect(
                                    new VisitorStats(
                                            "", "",
                                            vc, ch, ar, is_new,
                                            0L, 0L, 1L, 0L, 0L,
                                            ts)
                            );
                        }
                    }
                });

        //5.返回union后的数据
        return pvAndDurationStream.union(uvStream, jvStream, svStream);
    }
}
